package com.tnl.hunter.wechat.interceptor;

import com.biz.wechat.annotation.OAuthRequired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

public class TestInterceptor implements HandlerInterceptor {
	
	private static Logger logger = LoggerFactory.getLogger(TestInterceptor.class);
	
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.debug("**process sequence 3、afterCompletion**");
	}


	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2, ModelAndView modelAndView)
			throws Exception {
		logger.debug("**process sequence: 2、postHandle**");
	}

	/**
	 * * 在业务处理器处理请求之前被调用 
	 * 如果返回false 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
	 * 如果返回true 执行下一个拦截器,直到所有的拦截器都执行完毕 再执行被拦截的Controller 然后进入拦截器链,
	 * 从最后一个拦截器往回执行所有的postHandle() 接着再从最后一个拦截器往回执行所有的afterCompletion()
	 */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		logger.debug("**process sequence: 1、preHandle**");
		String url = request.getRequestURL().toString();
		HttpSession session = request.getSession();

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		OAuthRequired annotation = method.getAnnotation(OAuthRequired.class);
		if (annotation != null) {
			session.setAttribute("OpenId", "o852IsxjLjGA0kmPlF0bQ2suht0Y");
//		oWqHpjiTTSB9HPswwafLyywJaTpM kevin
//				o852IsxjLjGA0kmPlF0bQ2suht0Y    vian
		}
		return true;
	}
}